package x.ovo.wechat.bot;

import lombok.extern.slf4j.Slf4j;
import x.ovo.wechat.bot.common.command.Command;
import x.ovo.wechat.bot.common.command.CommandExecutor;
import x.ovo.wechat.bot.common.entity.message.TextMessage;
import x.ovo.wechat.bot.common.plugin.Plugin;
import x.ovo.wechat.bot.common.plugin.PluginDescription;

import java.util.*;
import java.util.function.Function;

@Slf4j(topic = "插件管理")
public class ManagerCommandExecutor extends CommandExecutor {


    protected ManagerCommandExecutor(Plugin plugin) {
        super(plugin);
    }

    @Override
    public void execute(Command command, TextMessage message) {
        String fromName = command.getFromName();
        String[] args = command.formatArgs();

        if (!inAuthors(fromName)) {
            this.context.getApi().sendText(message.getFromUser().getUserName(), "你没有权限执行此命令，不要调皮");
            return;
        }

        String result = this.help().apply(null);
        String fromUsername = message.isGroup() ? message.getFromUser().getNickName() : "";
        try {
            switch (args[0]) {
                case "help" -> result = this.help().apply(null);
                case "enable" -> result = this.enable(fromUsername).apply(args.length == 1 ? null : args[1]);
                case "disable" -> result = this.disable(fromUsername).apply(args.length == 1 ? null : args[1]);
                case "load" -> result = this.load().apply(args.length == 1 ? null : args[1]);
                case "reload" -> result = this.reload().apply(args.length == 1 ? null : args[1]);
                case "unload" -> result = this.unload().apply(args.length == 1 ? null : args[1]);
                case "list" -> result = this.list(fromUsername).apply(null);
                case "info" -> result = this.info().apply(args.length == 1 ? null : args[1]);
                default -> {
                }
            }
            this.context.getApi().sendText(message.getFromUser().getUserName(), result);
        } catch (Exception e) {
            log.error("命令执行失败", e);
            this.context.getApi().sendText(message.getFromUser().getUserName(), "命令执行失败" + e.getMessage());
        }
    }

    private Function<String, String> help() {
        return s -> """
                [插件管理]插件帮助：
                ---------------
                help                显示帮助
                list                显示插件列表
                detail <plugin>     插件详情
                enable <plugin>     启用插件
                disable <plugin>    禁用插件
                load <plugin>       加载插件
                unload <plugin>     卸载插件
                reload <plugin>     重载插件
                """;
    }

    private Function<String, String> list(String name) {
        return s -> {
            Collection<String> plugins = this.context.getPluginManager().getPlugins();
            Set<String> set = this.context.getPluginManager().listGroupPlugins(name);
            String string = "插件列表\n---------------\n" + String.join("\n", plugins);
            if (set != null && !set.isEmpty()) {
                string += "\n---------------\n本群已启用插件：\n" + String.join("\n", set);
            }
            return string;
        };
    }

    private Function<String, String> enable(String name) {
        return s -> {
            if (Objects.isNull(s) || s.isEmpty()) return "请输入插件名称";
            List<String> success = new ArrayList<>();
            List<String> error = new ArrayList<>();
            Arrays.stream(s.split(","))
                    .distinct()
                    .forEach(plugin -> {
                        if (this.context.getPluginManager().getPlugin(plugin) == null) {
                            error.add(plugin);
                        } else {
                            this.context.getPluginManager().enablePlugin(plugin, name);
                            this.context.getPluginManager().saveConfig();
                            success.add(plugin);
                        }
                    });
            return (Objects.equals(name, "") ? "本群" : "") +
                    (success.isEmpty() ? "" : "插件 " + success + " 已成功启用，") +
                    (error.isEmpty() ? "" : "插件 " + error + " 不存在");
        };
    }

    private Function<String, String> disable(String name) {
        return s -> {
            if (Objects.isNull(s) || s.isEmpty()) return "请输入插件名称";
            List<String> success = new ArrayList<>();
            List<String> error = new ArrayList<>();
            Arrays.stream(s.split(","))
                    .distinct()
                    .forEach(plugin -> {
                        if (this.context.getPluginManager().getPlugin(plugin) == null) {
                            error.add(plugin);
                        } else {
                            this.context.getPluginManager().disablePlugin(plugin, name);
                            this.context.getPluginManager().saveConfig();
                            success.add(plugin);
                        }
                    });
            return (Objects.equals(name, "") ? "本群" : "") +
                    (success.isEmpty() ? "" : "插件 " + success + " 已成功启用，") +
                    (error.isEmpty() ? "" : "插件 " + error + " 不存在");
        };
    }

    private Function<String, String> load() {
        return s -> {
            if (Objects.isNull(s) || s.isEmpty()) return "请输入插件名称";
            this.context.getPluginManager().loadPlugin(s);
            return "插件 [" + s + "] 已成功加载";
        };
    }

    private Function<String, String> unload() {
        return s -> {
            if (Objects.isNull(s) || s.isEmpty()) return "请输入插件名称";
            this.context.getPluginManager().unloadPlugin(s);
            return "插件 [" + s + "] 已成功卸载";
        };
    }

    private Function<String, String> reload() {
        return s -> {
            if (Objects.isNull(s) || s.isEmpty()) return "请输入插件名称";
            this.context.getPluginManager().unloadPlugin(s);
            this.context.getPluginManager().loadPlugin(s);
            return "插件 [" + s + "] 已成功重载";
        };
    }

    private Function<String, String> info() {
        return s -> {
            if (Objects.isNull(s) || s.isEmpty()) return "请输入插件名称";
            Plugin plugin = this.context.getPluginManager().getPlugin(s);
            if (Objects.isNull(plugin)) return "插件 [" + s + "] 不存在";
            PluginDescription description = plugin.getDescription();
            StringBuilder sb = new StringBuilder();
            sb.append("插件名称：").append(description.getName()).append("\n");
            sb.append("插件版本：").append(description.getVersion()).append("\n");
            sb.append("插件作者：").append(String.join(",", description.getAuthors())).append("\n");
            if (Objects.nonNull(description.getDescription())) {
                sb.append("插件描述：").append(description.getDescription()).append("\n");
            }
            if (Objects.nonNull(description.getCommands())) {
                sb.append("插件指令：").append(String.join(",", description.getCommands())).append("\n");
            }
            if (Objects.nonNull(description.getMain())) {
                sb.append("插件主类：").append(description.getMain()).append("\n");
            }

            return "插件 [" + s + "] 信息\n---------------\n" + sb;
        };
    }

}
